﻿using InfonavaEye.common;
using InfonavaEye.model;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Media;
using Color = System.Drawing.Color;

namespace InfonavaEye.components
{
    public class BoxTemplatePreview
    {
        Color mainColor = Color.FromArgb(255, 180, 180, 180);
        public readonly int margin = 600;
        public readonly int paddingTop = 900;
        public readonly int paddingBottom = 300;
        public readonly int paddingH = 500;
        public readonly int nailWidth = 400;
        public readonly int nailHeight = 400;
        /// <summary>
        /// 画布缩放比率
        /// </summary>
        public  float scaleRate = 1 / 18f;
        //Dictionary<string, Nail> nailMap = new Dictionary<string, Nail>();

        /// <summary>
        ///  选择钉盒模板时选中的钉子的字典
        /// </summary>
        private Dictionary<String, Nail> nailListToMap = null;

        PictureBox picPreview;
        BoxModel boxModel;
        public List<Nail> nailList = new List<Nail>();
        Graphics drawG = null;
        public int maxNailCount = 0;

        public event Action<NailStatus> updateNailCountDelegate;

        public void drawAreas(PictureBox picPreview,BoxModel boxModel)
        {
            this.picPreview = picPreview;
            this.boxModel = boxModel;

            if (drawG == null)
            {
                drawG = picPreview.CreateGraphics();
                GraphicsHelper.SetGDIHigh(drawG);
            }

            Color areaColor = Color.FromArgb(255, 250, 250, 250);
            Color bgColor = Color.FromArgb(255, 233, 233, 233);
            GraphicsHelper.FillRoundRectangle(picPreview.ClientRectangle, drawG, 15, bgColor);

            if (boxModel == null || boxModel.boxAreas == null || boxModel.boxAreas.Count == 0) return;

            maxNailCount = 0;
            nailList.Clear();
            int minX = (boxModel.boxAreas.Min(p => p.startPoint[0]));
            int minY = (boxModel.boxAreas.Min(p => p.startPoint[1]));
            int maxX = (boxModel.boxAreas.Max(p => p.startPoint[0]));
            int maxY = (boxModel.boxAreas.Max(p => p.startPoint[1]));
            int maxWidth = maxX - minX;
            int maxHeight = maxY - minY;
            int fixX = 0 - minX;
            int fixY = 0 - minY;

            boxModel.boxAreas.ForEach((area) =>
            {
                maxNailCount += area.rowCount * area.columnCount;

                try
                {
                    Console.WriteLine("绘制区域:" + area.name);
                    var startPoint = area.startPoint;
                    var columnTitles = area.columnTitle;

                    //画外框
                    var x = startPoint[0] + fixX + margin;
                    var y = startPoint[1] + fixY + margin;
                    var width = area.holdPitch[0] * (area.columnCount - 1) + 2 * (paddingH);
                    var height = area.holdPitch[1] * (area.rowCount - 1) + (paddingTop + paddingBottom);
                    var newPoint = flipXY(picPreview,(int)(x * scaleRate), (int)(y * scaleRate));
                    //Console.WriteLine("绘制区域参数：x {0}，y {1},width {2},height {3}", x * scaleRate, y * scaleRate, width * scaleRate, height * scaleRate);
                    var areaPath = GraphicsHelper.DrawRoundRect((int)newPoint.X - (int)(width * scaleRate), (int)newPoint.Y - (int)(height * scaleRate), (int)(width * scaleRate), (int)(height * scaleRate), 15);
                    //drawG.Clear(picPreview.BackColor);
                    drawG.DrawPath(new System.Drawing.Pen(areaColor, 1), areaPath);
                    //画螺钉
                    for (int i = 0; i < area.columnCount; i++)
                    {
                        for (int j = 0; j < area.rowCount; j++)
                        {
                            width = nailWidth;
                            height = nailHeight;
                            /*if (i == 0 && j == 0)
                            {
                                width = (int)Math.Round(nailWidth * 1.5, 0);
                                height = (int)Math.Round(nailWidth * 1.5, 0);
                            }*/
                            x = startPoint[0] + fixX + area.holdPitch[0] * i + paddingH + margin - (width) / 2;
                            y = startPoint[1] + fixY + area.holdPitch[1] * j + paddingTop + margin - (height) / 2;
                            newPoint = flipXY(picPreview, (int)(x * scaleRate), (int)(y * scaleRate));
                            Rectangle r = new Rectangle((int)newPoint.X - (int)(width * scaleRate), (int)newPoint.Y - (int)(height * scaleRate), (int)(width * scaleRate), (int)(height * scaleRate));

                            var nailKey = string.Format(AutoStartParams.NAIL_MAP_KEY_FORMAT, area.code, i, j);
                            bool selected = (this.nailListToMap != null && this.nailListToMap.ContainsKey(nailKey) && this.nailListToMap[nailKey].status == NailStatus.Selected);
                            //默认选中所有钉子
                            if (this.nailListToMap == null)
                            {
                                selected = true;
                            }
                            var nailStatus = selected ? NailStatus.Selected : NailStatus.Normal;
                            if (selected && updateNailCountDelegate!=null) { updateNailCountDelegate.Invoke(nailStatus); }
                            var nail = new Nail()
                            {
                                status = nailStatus,
                                area = area,
                                point = new Point(i, j),
                                location = r,
                                updateTime = DateTime.Now,
                            };
                            nailList.Add(nail);
                            //Console.WriteLine("绘制钉子 ({0})：x {1}，y {2},width {3},height {4}", i + ":" + j, x * scaleRate, y * scaleRate, width * scaleRate, height * scaleRate);
                            //drawG.DrawImage(selected ? Properties.Resources.nail_plus : Properties.Resources.nail_empty, r);
                            drawNail(nail);

                            //第一排头部写上数字
                            if (j == 0 && (columnTitles.Count() - 1) >= i)
                            {
                                drawText(drawG, r, columnTitles[i]);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("绘制区域发生异常：{0}，{1}", ex.Message, ex.StackTrace);
                }
            });
            drawG.Dispose();
            drawG = null;
        }

        private void drawText(Graphics graphics, Rectangle nailRect, string text)
        {
            var enlargeWidth = 40;
            var enlargeHeight = 10;
            Rectangle textRect = new Rectangle(nailRect.X - enlargeWidth / 2, nailRect.Y + 35 - enlargeHeight / 2, nailRect.Width + enlargeWidth, nailRect.Height + enlargeHeight);
            Font LabelFont = new Font("黑体", 12, FontStyle.Regular); //设置字体、字号、是否加粗
            SolidBrush labelColor = new SolidBrush(Color.FromArgb(255, 99, 99, 99));//设置字体颜色
            StringFormat sf = new StringFormat();//位置对象
            sf.Alignment = StringAlignment.Center;//居中
            graphics.DrawString(text, LabelFont, labelColor, textRect, sf);
        }

        Color bgColor = Color.FromArgb(255, 233, 233, 233);

        public void drawNail(Nail nail)
        {
            if (drawG == null)
            {
                drawG = this.picPreview.CreateGraphics();
                GraphicsHelper.SetGDIHigh(drawG);
            }
            var point = nail.point;
            GraphicsHelper.FillRoundRectangle(nail.location, drawG, 15, bgColor);
            //Console.WriteLine("绘制钉子 ({0})：x {1}，y {2},width {3},height {4},status:{5}", point.X + ":" + point.Y, nail.location.X, nail.location.Y, nail.location.Width, nail.location.Height, nail.status);
            var img = nail.status == NailStatus.Normal ? Properties.Resources.nail_empty : Properties.Resources.nail_plus;
            drawG.DrawImage(img, nail.location);
        }


        public void selectAllNail(bool checkAll)
        {
            if (this.boxModel == null || this.boxModel.boxAreas == null) return;

            this.boxModel.boxAreas.ForEach((area) =>
            {
                var startPoint = area.startPoint;

                for (int i = 0; i < nailList.Count; i++)
                {
                    var nail = nailList[i];
                    var newStatus = (checkAll) ? NailStatus.Selected : NailStatus.Normal;
                    //if (nail.status == newStatus) return;
                    nail.status = newStatus;
                    drawNail(nail);
                }
            });
           
        }

        /// <summary>
        /// 翻转X轴坐标
        /// （使图像本来显示在左侧的，现在显示到右侧）
        /// </summary>
        private System.Windows.Point flipXY(PictureBox picPreview, int x, int y)
        {
            int centerX = picPreview.Width / 2;
            int centerY = picPreview.Height / 2;
            var transform = new RotateTransform() { Angle = 180, CenterX = centerX, CenterY = centerY };
            return transform.Transform(new System.Windows.Point(x, y));
        }
    }
}
